package com.example.zzpneo4j.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.example.zzpneo4j.config.SpringContextUtil;
import com.example.zzpneo4j.dto.ExamMsg;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ExcelService extends AnalysisEventListener<Map<Integer, String>> {

    private String url;
    private String fileName;
    private String labels;

    public static final String UTF8_BOM = "\uFEFF";


    public void setUrl(String url) {
        this.url = url;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setLabels(String labels) {
        this.labels = labels;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        ExamMsg examMsg = JSONObject.parseObject(JSONObject.toJSONString(data), ExamMsg.class);
        System.out.println(examMsg);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("解析到的表头数据: {}", headMap.entrySet());
        Neo4jService neo4jService = SpringContextUtil.getBean(Neo4jService.class);


        String lineName = headMap.values().stream()
                .map(line -> {
                    if (line.startsWith(UTF8_BOM)) {
                        line = line.substring(1);
                    }
                    return line.trim() + ":line." + line.trim();
                })
                .collect(Collectors.joining(","));
        lineName += ",createTime:'" + LocalDateTime.now() + "'";
        System.out.println(lineName);
        neo4jService.loadCsv(lineName, url, fileName, labels);
    }


}
